﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.WebControls;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class TaskRegisterBasic :BasePage
    {
        String sqlCategory = "select * from dbo.Cms_Ctrt_InstrumentCategory where SUBSTRING(categoryCode,1,2)='02' ";

        public Guid RegisterID
        {
            get
            {
                if (hiddenRegisterID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenRegisterID.Value);
            }
            set
            {
                hiddenRegisterID.Value = value.ToString();
            }
        }

        public string TaskRegisterSource
        {
            get
            {
                if (Request.QueryString["TaskRegisterSource"] != null) return Request.QueryString["TaskRegisterSource"].ToString();
                else return "0";
            }
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {

                txt_SQLID_Category.Text = Guid.NewGuid().ToString();
                Session.Add(txt_SQLID_Category.Text, sqlCategory);
                InstrumentTypeSelect.OnClientClick = JsExtension.CreateModalWindowScript("../Lookup/TreeSelect.aspx?SQLID=" + txt_SQLID_Category.Text + "&NameField=categoryName&ValueField=categoryGUID&RelationField=parentGUID", returnValue.ClientID, 420, 320);
                EnumeratorHelper[] helper = EnumeratorHelper.GetFieldTexts(typeof(Enumerator.SalesService));              
                TaskType.BindEnum(helper);

                
                employeeName.Text = base.CurrentUserEntity.UserName;
                employeeGUID.Value = base.CurrentUserID.ToString();
                RegisterDate.SelectedDate = DateTime.Now;
                TaskType.SelectedValue = "2";
                if (Request.QueryString["RegisterID"] != null)
                {
                    TaskType.Enabled = false;

                    RegisterID = new Guid(Request.QueryString["RegisterID"]);

                    SystemBll bll = new SystemBll();
                    WsmTaskRegisterEntity entity = new WsmTaskRegisterEntity();
                    if (RegisterID != Guid.Empty)
                    {
                        entity = bll.Get<WsmTaskRegisterEntity>(RegisterID);
                    }
                    agentGUID.Value = entity.Agent;
                    TaskType.SelectedValue = entity.TaskType.ToString();
                    Comment.Text = entity.Comment;
                    hiddenUserID.Value = entity.CustomerID.ToString();
                    ExpectEndDate.SelectedDate = entity.ExpectEndDate;

                    employeeGUID.Value = entity.PerformPerson.ToString();
                    InstrumentType.Value = entity.InstrumentType;
                    hiddenInstrumentID.Value = entity.InstrumentID.ToString();
                    if (entity.TaskType != 1)
                    {
                        hiddenInstrumentIDOther.Value = entity.InstrumentID.ToString() + "|" + entity.InstrumentSerialNum;
                    }
                    if (InstrumentType.Value != "")
                    {
                        InstrumentTypeName.Text = new SystemBll().Get<CtrtInstrumentCategoryEntity>(new Guid(InstrumentType.Value)).categoryName;
                    }
                    if (hiddenInstrumentID.Value != Guid.Empty.ToString())
                    {
                        hiddenInstrumentName.InnerHtml = new SystemBll().Get<WsmInstrumentInfoEntity>(new Guid(hiddenInstrumentID.Value)).instrumentName;
                        hiddenInstrumentNameOther.InnerHtml = new SystemBll().Get<WsmInstrumentInfoEntity>(new Guid(hiddenInstrumentID.Value)).instrumentName;
                    }
                    RegisterDate.SelectedDate = entity.RegisterDate;
                    hiddenuserName.InnerHtml = new SystemBll().Get<CtrtCustomerEntity>(new Guid(hiddenUserID.Value)).CustomerName;

                    //客户区域
                    WsmCustomerExtensionEntity CusExtEntity = new SystemBll().Get<WsmCustomerExtensionEntity>(entity.CustomerID);
                    if (CusExtEntity != null)
                    {
                        ddlCustomerArea.SelectedValue = CusExtEntity.CustomerArea;
                    }

                    SysUserEntity userEntity;
                    if (employeeGUID.Value != null && employeeGUID.Value != "")
                    {
                        userEntity = new SystemBll().Get<SysUserEntity>(new Guid(employeeGUID.Value));
                        employeeName.Text = userEntity.UserName;
                    }
                    if (agentGUID.Value != null && agentGUID.Value != "")
                    {
                        userEntity = new SystemBll().Get<SysUserEntity>(new Guid(agentGUID.Value));
                        agentName.Text = userEntity.UserName;
                    }
                    if (entity.IsSystemAssign)
                    {
                        TaskType.Enabled = false;
                    }
                    txtInstrumentSerialNum_ex.Text = entity.InstrumentSerialNum_ex;
                }
                else
                {
                    int i;
                    ListItem li;

                    //if (base.CheckUserHasFuction(1, "Func5013")) { return; }

                    for (i = TaskType.Items.Count - 1; i >= 0; i--)
                    {
                        li = TaskType.Items[i];

                        if (Convert.ToInt16(li.Value) == 1 && !base.CheckUserHasFuction(1, "Func5092"))
                        { TaskType.Items.Remove(li); }

                        if (Convert.ToInt16(li.Value) > 20 && !base.CheckUserHasFuction(1, "Func5013") && Convert.ToInt16(li.Value) != 26 && Convert.ToInt16(li.Value)!=32)
                        { TaskType.Items.Remove(li); }
                    }
                }

            }
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            if (Request.Headers["Accept"] == "*/*") { return; }
            string Message = "";
            if (!save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else if (TaskRegisterSource == "0")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.opener.document.getElementById('ctl00_cphBody_btnRefersh').click();window.close();", true);
            }
            else { ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.opener=null;window.open('','_self');window.close();", true); }
        }


        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (Request.Headers["Accept"] == "*/*") { return; }
            if (!save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
                return;
            }

            if (TaskRegisterSource == "0")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('保存成功');window.opener.document.getElementById('ctl00_cphBody_btnRefersh').click();", true);
            }
            else { ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true); }

            
            Response.Redirect("../ContractFollowUp/TaskRegisterBasic.aspx");
            //hiddenRegisterID.Value = "";
            //TaskType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.SalesService)));
            //RegisterDate.SelectedDate = DateTime.Now;
        }        

        private bool save(ref string message) {
            if(!validateCheck(ref message)){                
                return false;
            }
            bool isSuccess = true;
            WsmTaskRegisterEntity entity = new WsmTaskRegisterEntity();
            SystemBll bll = new SystemBll();
            if (RegisterID != Guid.Empty)
            {
                entity = bll.Get<WsmTaskRegisterEntity>(RegisterID);
            }
            else
            {
                entity = new WsmTaskRegisterEntity();
                RegisterID = entity.RegisterID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;
                entity.TaskStatus = 0;
                entity.IsSystemAssign = false;
                entity.Deleted = false;
            }
            entity.Agent = agentGUID.Value.ToString();
            entity.Comment = Comment.Text.Trim();       
            entity.CustomerID = new Guid(hiddenUserID.Value);
            entity.InstrumentSerialNum_ex = txtInstrumentSerialNum_ex.Text.Trim();
            if(ExpectEndDate.SelectedDate != null)
                entity.ExpectEndDate = ExpectEndDate.SelectedDate.Value;
            if (TaskType.SelectedValue != "1" && hiddenInstrumentIDOther.Value.Trim() !="")
            {
                entity.InstrumentID = new Guid(hiddenInstrumentIDOther.Value.Trim().Split(new char[]{'|'})[0]);
                entity.InstrumentSerialNum = hiddenInstrumentIDOther.Value.Trim().Split(new char[] { '|' })[1];
            }
            else if (hiddenInstrumentID.Value!="") {
                entity.InstrumentID = new Guid(hiddenInstrumentID.Value);
            }
            if (hiddenInstrumentID.Value != "")
            {
                entity.InstrumentType = new SystemBll().Get<WsmInstrumentInfoEntity>(entity.InstrumentID).CategoryGUID.ToString();
            }
            entity.PerformPerson = new Guid(employeeGUID.Value);
            if (RegisterDate.SelectedDate != null)
                entity.RegisterDate = RegisterDate.SelectedDate.Value;
            entity.TaskType = System.Convert.ToInt32(TaskType.SelectedValue);
            bll.InsertOrUpdate(entity);

            //保存用户区域
            WsmCustomerExtensionEntity CusEntity = bll.Get<WsmCustomerExtensionEntity>(new Guid(hiddenUserID.Value));
            if (CusEntity != null)
            {
                CusEntity.CustomerArea = ddlCustomerArea.SelectedValue;
                bll.Update(CusEntity);
            }

            //WsmMaintainBillEntity mainEntity 
            List<WsmMaintainBillEntity> list = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID='" + RegisterID + "'");
            if (list != null && list.Count > 0)
            {
                WsmMaintainBillEntity mainEntity = list[0];
                if (mainEntity != null && hiddenInstrumentIDOther.Value != "")
                {
                    mainEntity.InstrumentSerialNum = hiddenInstrumentIDOther.Value.Trim().Split(new char[] { '|' })[1];
                    bll.Update(mainEntity);
                }
            }
            return isSuccess;
        }

        private bool validateCheck(ref string message) {
            bool isValidate = true;
            if (hiddenUserID.Value.Trim() == "") {
                message = "请选择客户";
                isValidate = false;
            }
            if (TaskType.SelectedValue.ToString() != "1" && TaskType.SelectedValue.ToString() != "8" && Convert.ToInt16(TaskType.SelectedValue.ToString()) < 12 && hiddenInstrumentIDOther.Value.Trim() == "")
            {
                message = "请选择仪器";
                isValidate = false;
            }

            if (TaskType.SelectedValue.ToString() == "1" && hiddenInstrumentID.Value.Trim() == "")
            {
                message = "请选择仪器";
                isValidate = false;
            }

            if (employeeGUID.Value.Trim() == "") {
                message = "请选择执行人";
                isValidate = false;
            }
            if (RegisterDate.SelectedDate == null) {
                message = "请填写注册时间";
                isValidate = false;
            }
            if (ExpectEndDate.SelectedDate == null) {
                message = "请填写期望完成日期";
                isValidate = false;
            }
            return isValidate;
        }
        protected void InstrumentTypeSelect_Click(object sender, ImageClickEventArgs e)
        {
            if (hiddenUserID.Value != "")
            {
                hiddenuserName.InnerHtml = new SystemBll().Get<CtrtCustomerEntity>(new Guid(hiddenUserID.Value)).CustomerName;
            }
            if (returnValue.Value != "")
            {
                InstrumentTypeName.Text = returnValue.Value.Split('|')[0];
                InstrumentType.Value = returnValue.Value.Split('|')[1];
                returnValue.Value = "";
              
                if (TaskType.SelectedValue == "1")             
                {
                    ScriptManager.RegisterStartupScript(this,this.GetType(), "saa", "taskTypeChange();document.getElementById('parmT').additionalparams='categoryGUID=" + InstrumentType.Value + "';", true);
                }
            }
        }
    }
}
